package exp07gui;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * Java Swing模仿Windows自带的计算器:
 * GUI复杂界面生成
 */
public class Calculator0 extends JFrame implements ActionListener {
    JTextField jTextFieldA;
    JTextField jTextFieldB;
    JButton jButtonEqual;
    JLabel jLabelResult;

    public Calculator0() {
        setLayout(new FlowLayout());
        this.add(jTextFieldA = new JTextField(10));
        this.add(new JLabel("+"));
        this.add(jTextFieldB = new JTextField(10));
        this.add(jButtonEqual = new JButton("="));
        jButtonEqual.addActionListener(this);
        this.add(jLabelResult = new JLabel("N/A"));

        this.setResizable(false);// 禁用最大化按钮
        this.pack();
        setTitle("My Calculator ver 0.1a");
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == jButtonEqual) {
            System.err.println("jButtonEqual +clicked");
            double a = 0, b = 0;
            boolean flag = true;
            try {
                a = Integer.parseInt(jTextFieldA.getText());

            } catch (Exception ee) {
                jTextFieldA.setText("0");
                flag = false;
            }
            try {
                b = Integer.parseInt(jTextFieldB.getText());
            } catch (Exception ee) {
                jTextFieldB.setText("0");
                flag = false;
            }
            if (flag)
                jLabelResult.setText(Double.toString(a + b));


        }
    }

    public static void main(String[] args) {
        String s = null;
        // s.equal("admin")            "admin".equals(s)//robust

        new Calculator0();
    }
}